<template>
  <div class="list">
    <van-pull-refresh
      v-model="refreshing"
      @refresh="onRefresh"
    >
      <van-list
        v-model="loading"
        :finished="finished"
        :finished-text="!loading && list.length === 0 ? '' : '已加载全部'"
        @load="onLoad"
      >
        <van-empty
          v-if="!loading && list.length === 0"
          description="还没有数据"
        />
        <slot v-else />
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
export default {
  name: "ScrollList",
  props: {
    list: {
      type: Array,
      default: () => [],
    },
  },
  model: {
    prop: "list",
    event: "updateList",
  },
  data() {
    return {
      // 分页
      page: 1,
      // 加载状态
      loading: false,
      // 是否完成
      finished: false,
      // 是否刷新
      refreshing: false,
    };
  },
  methods: {
    async onLoad() {
      // 如果是刷新状态 先执行清空列表
      if (this.refreshing) {
        this.$emit("updateList", []);
        this.refreshing = false;
      }

      // 发送获取数据请求
      this.$emit('onLoad', this.page, (finished) => {
        this.page ++;

        // 关闭加载动画
        this.loading = false;

        // 设置列表完全标识
        this.finished = finished;
      })
    },
    refresh() {
      this.refreshing = true;
      this.onRefresh();
    },
    onRefresh() {
      // 取消列表完全状态
      this.finished = false;

      // 设置加载状态
      this.loading = true;

      // 重置分页
      this.page = 1;

      // 触发加载
      this.onLoad();
    }
  }
};
</script>

<style lang="scss" scoped>
.list {
  flex: 1;
  height: 0;
  .van-pull-refresh {
    height: 100%;
    overflow-y: auto;
  }
}
</style>
